import React, { useState } from "react";

import {
  Grid,
  FormControlLabel,
  Checkbox,
  Button,
  InputAdornment,
  IconButton,
  TextField,
} from "@material-ui/core";
import { useForm } from "react-hook-form";

import Visibility from "@material-ui/icons/Visibility";
import VisibilityOff from "@material-ui/icons/VisibilityOff";

import { useStatusListener } from "../../hooks/useStatusListener";
import { formValidation } from "../../helpers/validation";
import { Link, useHistory } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { useRequest } from "../../hooks/useRequest";
import { POST_REGISTER_USER } from "../../config/api";
import { useSnackbar } from "notistack";

type FormSignupData = {
  username: string;
  email: string;
  password: string;
};

export default function SignUpPage() {
  const { t } = useTranslation();
  const history = useHistory();
  const [userEmail, setUserEmail] = useState("");
  const { fetchData, state: requestState } = useRequest();
  const { register, handleSubmit, errors } = useForm<FormSignupData>();
  const handleClickShowPassword = () => setShowPassword(!showPassword);
  const [checked, setChecked] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const { enqueueSnackbar } = useSnackbar();
  const backgroundImage = require("../../assets/images/LoginPage/backgroundImage.jpg");
  const logo = require("../../assets/images/LoginPage/logo.svg");

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setChecked(event.target.checked);
  };

  const onSubmit = (data: FormSignupData) => {
    setUserEmail(data.email);
    fetchData(POST_REGISTER_USER, data);
  };
  const onSuccess = () => {
    history.replace(`/emailVerifySent/${userEmail}`);
  };
  const onReject = () => {
    if (requestState.error?.message) {
      enqueueSnackbar(requestState.error?.message, {
        variant: "error",
        autoHideDuration: 3000,
      });
    }
  };

  // const onReject = () => {
  //    enqueueSnackbar(requestState.error.message);
  // };
  useStatusListener(requestState.status, onSuccess, onReject);

  // sign up styles resource loginPage styles
  return (
    <>
      <div className="app-wrapper min-vh-100 bg-white">
        <div className="app-inner-content-layout--main app-content p-0">
          <div className="bg-composed-wrapper--content flex-grow-1 w-100 d-flex align-items-center">
            <Grid container spacing={0} className="min-vh-100 ">
              <Grid item lg={5} xl={6} className="d-flex">
                <div className="background-gradient">
                  <img
                    src={backgroundImage}
                    alt="background"
                    className="background-image"
                  />
                  <div className="left-box-content">
                    <div className="greeting-box">
                      <img
                        src={logo}
                        alt="bitbine-logo"
                        className="logo-image"
                      />
                      <div className="greeting-text font-size-xxxl my-4">
                        {t("form:welcome-bitbine")}
                      </div>
                    </div>
                    <div className="left-box-bottom font-size-xxl mx-auto">
                      {t("form:form-desc")}
                    </div>
                  </div>
                </div>
              </Grid>
              <Grid item lg={7} xl={6} className="d-flex align-items-center">
                <Grid
                  item
                  md={10}
                  lg={8}
                  xl={7}
                  className="mx-auto signup-box-form"
                >
                  <div className="py-4">
                    <div className="form-header text-center">
                      <div className="display-4 mb-1  form-title">
                        {t("form:signup")}
                      </div>
                      <p className="font-size-lg  text-black-50 mt-2">
                        {t("form:signup-greeting")}
                      </p>
                    </div>

                    <form onSubmit={handleSubmit(onSubmit)}>
                      <div>
                        <TextField
                          fullWidth
                          id="username"
                          name="username"
                          placeholder={t("form:username")}
                          className="form-input my-2"
                          inputRef={register(formValidation.username)}
                          helperText={
                            errors.username?.message &&
                            t(`${errors.username?.message}`)
                          }
                          error={Boolean(errors.username?.message)}
                        />
                      </div>
                      <div>
                        <TextField
                          fullWidth
                          name="email"
                          placeholder={t("form:email")}
                          className="form-input my-2"
                          inputRef={register(formValidation.email)}
                          helperText={
                            errors.email?.message &&
                            t(`${errors.email?.message}`)
                          }
                          error={Boolean(errors.email?.message)}
                        />
                      </div>
                      <div className="mb-2">
                        <TextField
                          fullWidth
                          name="password"
                          type={showPassword ? "text" : "password"}
                          placeholder={t("form:password")}
                          className="pass-input my-2 "
                          inputRef={register(formValidation.password)}
                          helperText={
                            errors.password?.message &&
                            t(`${errors.password?.message}`)
                          }
                          error={Boolean(errors.password?.message)}
                          style={{ height: "3.5rem" }}
                          InputProps={{
                            // <-- This is where the toggle button is added.
                            endAdornment: (
                              <InputAdornment position="end">
                                <IconButton
                                  aria-label="toggle password visibility"
                                  onClick={handleClickShowPassword}
                                >
                                  {showPassword ? (
                                    <Visibility />
                                  ) : (
                                    <VisibilityOff />
                                  )}
                                </IconButton>
                              </InputAdornment>
                            ),
                          }}
                        />
                      </div>
                      <div className="d-flex justify-content-between align-items-center font-size-md mt-4 ml-2">
                        <FormControlLabel
                          control={
                            <Checkbox
                              checked={checked}
                              onChange={handleChange}
                              value="checked1"
                              color="primary"
                              required
                            />
                          }
                          label="I agree with terms and conditions"
                        />
                      </div>
                      <div className="text-center py-4">
                        <Button
                          className="btn-primary font-weight-bold my-2 p-4"
                          type="submit"
                          style={{ width: "40%" }}
                        >
                          {t("form:signup")}
                        </Button>
                      </div>
                      <Link to="/login">
                        <div className="text-primary text-center already-account ">
                          {t("form:already-account")}
                        </div>
                      </Link>
                    </form>
                  </div>
                  <div className="form-bottom">
                    <h6 className="terms">
                      <span className="mr-3">{t("form:terms")}</span>
                    </h6>
                    <h6 className="privacy ml-4">{t("form:privacy")}</h6>
                  </div>
                </Grid>
              </Grid>
            </Grid>
          </div>
        </div>
      </div>
    </>
  );
}
